use std::process::{Command, Stdio};
// 1.简单执行命令
fn bassic_command() -> Result<(), Box<dyn std::error::Error>> {
    let output = Command::new("ls")
        .arg("-l")
        .output()?;
    println!("状态:{}",output.status);
    println!("stdout: {}",String::from_utf8_lossy(&output.stdout));
    println!("stderr: {}",String::from_utf8_lossy(&output.stderr));
    Ok(())
}
// 2.带参数命令
fn command_wiht_args() -> Result<(), Box<dyn std::error::Error>> {
    let status = Command::new("git")
        .args(["clone", "https://gitee.com/autumner/rust_learn_examples.git"])
        .status()?;
    if status.success(){
        println!("命令执行成功");
    }else {
        println!("命令执行失败");
    };
    Ok(())
}
// 3.管道和重定向
fn pipe_commands() -> Result<(), Box<dyn std::error::Error>> {
    let ps = Command::new("ps")
        .arg("aux")
        .stdout(Stdio::piped())
        .spawn()?;
    let grep = Command::new("grep")
        .arg("vnc")
        .stdin(Stdio::from(ps.stdout.unwrap()))
        .output()?;
    println!("{}", String::from_utf8_lossy(&grep.stdout));
    Ok(())
}
// 4.环境变量设置
fn env_command() -> Result<(), Box<dyn std::error::Error>> {
    let output = Command::new("printenv")
        .env("MY_VAR", "my_value")
        // .env_clear() //清除所有环境变量
        .env("PATH", "$PATH:/usr/local/bin:/usr/bin") //设置必要的PATH
        .output()?;
    println!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}
// 5.工作目录设置
use std::path::Path;
fn working_dir_command() -> Result<(), Box<dyn std::error::Error>> {
    let output = Command::new("ls")
        .current_dir(Path::new("/home/autumner"))
        .output()?;
    println!("{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}
fn main() {
    // let bc_cmd = bassic_command();
    // let arg_cmd = command_wiht_args();
    // pipe_commands().unwrap();
    // env_command().unwrap();
    // working_dir_command();
}
